package com.hyz.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hyz.pojo.assetImport.AssetImport;
import com.hyz.service.AssetImportService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

/**
 * @author HGD
 * @date 2022/10/4 14:07
 */
@Component
public class AssetImportListener {
    @Autowired
    private AssetImportService service;

    /**
     * 批量导入
     *
     * @param massage json字符串
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "assetImport.queue"),
            exchange = @Exchange(name = "assetManager", type = ExchangeTypes.DIRECT),
            key = {"batchInsertAssetImports"}
    ))
    public void batchInsertAssetImports(String massage) {
        ArrayList<AssetImport> assetImports = JSON.parseObject(massage, new TypeReference<ArrayList<AssetImport>>() {
        });
        service.saveBatch(assetImports);
    }

    /**
     * 批量更新
     *
     * @param massage json字符串
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "assetImport.queue"),
            exchange = @Exchange(name = "repositoryManager", type = ExchangeTypes.DIRECT),
            key = {"batchUpdateAssetImports"}
    ))
    public void batchUpdateAssetImports(String massage) {
        ArrayList<AssetImport> assetImports = JSON.parseObject(massage, new TypeReference<ArrayList<AssetImport>>() {
        });
        for (AssetImport assetImport : assetImports) {
            // 入库申请修改
            LambdaQueryWrapper<AssetImport> assetImportWrapper = new LambdaQueryWrapper<>();
            assetImportWrapper.eq(AssetImport::getAssetId, assetImport.getAssetId());
            service.update(assetImport, assetImportWrapper);
        }
    }
}
